package com.leessy.r229.server.http;/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import android.util.Base64;
import android.util.Log;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.leessy.r229.server.HttpApi;

import java.io.IOException;
import java.util.Arrays;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;


/**
 * @author : Created by liucheng. on 2021/01/19
 * @description : 加密处理
 */
public class EncryptInterceptor implements Interceptor {
    private static final String TAG = "EncryptInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
//        String url = request.url().toString();
        String method = request.method();
        if (/*isEncrypt(url) &&*/ method.equals("POST")) {
            RequestBody body = request.body();
            if (body == null) return chain.proceed(request);
            Buffer buffer = new Buffer();
            body.writeTo(buffer);
            byte[] contents = buffer.readByteArray();
            if (contents.length <= 0) return chain.proceed(request);
//            StringBuilder key = new StringBuilder("" + Config.INSTANCE.getHttpPass() + Config.INSTANCE.getDeviceNumber());
            byte[] keys = ConvertUtils.hexString2Bytes("e4e3e1ef9ee249328c4a1b6a0293c4dae4e3e1ef9ee24932");
//            while (key.length() < 16) {
//                key.append("0");/*补齐16位,最少*/
//            }
//            byte[] keys = EncryptUtils.encryptMD5(key.toString().getBytes());
//            if (keys.length != 24) {
//                Log.d(TAG, "intercept: 加密异常 key 长度异常 ,不加密处理");
//                return chain.proceed(request);
//            }
            String s = new String(contents);
            byte[] enrypt = EncryptUtils.encrypt3DES(
                    padWithZeros(s.getBytes("gbk")),
                    keys,
                    "DESede/ECB/NoPadding",
                    null
            );
            if (enrypt == null) {
                Log.d(TAG, "intercept: 加密异常 enrypt = null ");
                return chain.proceed(request);
            }
            request = request.newBuilder()/*重新配置请求头*/
                    .addHeader("signature", "true")/*标记为已经加密body*/
                    .post(RequestBody.create(mediaType, Base64.encode(enrypt, Base64.NO_WRAP)))
                    .build();
            return chain.proceed(request);
        }
        return chain.proceed(request);
    }

    private MediaType mediaType = MediaType.parse("text/plain");

    // 填充函数，将数据长度补齐为块大小的倍数
    public static byte[] padWithZeros(byte[] data) {
        int p = data.length % 8;
        if (p == 0) return data;
        int paddedLength = data.length + 8 - p;
        byte[] paddedData = Arrays.copyOf(data, paddedLength);
        // 填充0字节
        Arrays.fill(paddedData, data.length, paddedData.length, (byte) 0);
        return paddedData;
    }

    /*根据URL判断是否需要加密处理*/
    public boolean isEncrypt(String url) {
        if (url == null) return false;
        return (url.contains(HttpApi.HEARTBEAT)
        );
    }

}



